package com.guoheng.hazard.sys.service.impl.entpr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guoheng.hazard.common.base.Result;
import com.guoheng.hazard.common.constant.CommonConstants;
import com.guoheng.hazard.common.enums.ErrorCodeEnum;
import com.guoheng.hazard.common.enums.PartTypeEnum;
import com.guoheng.hazard.common.util.StringUtils;
import com.guoheng.hazard.sys.mapper.entpr.EntprBasicInfoMapper;
import com.guoheng.hazard.sys.mapper.entpr.MajorHazardMaterialMapper;
import com.guoheng.hazard.sys.mapper.entpr.StorageRoomMapper;
import com.guoheng.hazard.sys.model.dto.entpr.EntprScopeDTO;
import com.guoheng.hazard.sys.model.dto.entpr.StorageRoomInsertDTO;
import com.guoheng.hazard.sys.model.dto.entpr.StorageRoomSelectDTO;
import com.guoheng.hazard.sys.model.dto.entpr.StorageRoomUpdateDTO;
import com.guoheng.hazard.sys.model.dto.hazard.MajorHazardMaterialInsertDTO;
import com.guoheng.hazard.sys.model.dto.hazard.MajorHazardMaterialSelectDTO;
import com.guoheng.hazard.sys.model.entity.entpr.EntprBasicInfo;
import com.guoheng.hazard.sys.model.entity.entpr.MajorHazardMaterial;
import com.guoheng.hazard.sys.model.entity.entpr.StorageRoom;
import com.guoheng.hazard.sys.service.entpr.StorageRoomService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 类功能描述:　StorageRoomImpl
 *
 * @author fbl
 * @date 2019-11-12 18:15
 */
@Service
public class StorageRoomServiceImpl implements StorageRoomService {

    @Resource
    StorageRoomMapper storageRoomMapper;

    @Resource
    EntprBasicInfoMapper entprBasicInfoMapper;

    @Resource
    MajorHazardMaterialMapper majorHazardMaterialMapper;

    @Override
    public Result getEntprRooms(String entprName, String roomNo, Long entprId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<StorageRoomSelectDTO> entprRooms = storageRoomMapper.getEntprRooms(entprName, roomNo, entprId);
        for (StorageRoomSelectDTO entprRoom : entprRooms) {
            // 查询企业姓名
            Long eId = entprRoom.getEntprId();
            EntprBasicInfo entprBasicInfoById = entprBasicInfoMapper.getEntprBasicInfoById(eId);
            entprRoom.setEntprName(entprBasicInfoById.getEntprName());

            // 查询库房的介质
            List<MajorHazardMaterial> majorHazardMaterials = majorHazardMaterialMapper.getMajorMaterial(2, entprRoom.getId());
            entprRoom.setMajorHazardMaterials(majorHazardMaterials);
        }

        PageInfo<StorageRoomSelectDTO> storageRoomPageInfo = new PageInfo<>(entprRooms);
        return Result.success(storageRoomPageInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateEntprRooms(StorageRoomUpdateDTO storageRoomUpdateDTO) {
        // 修改库房信息
        StorageRoom storageRoom = new StorageRoom();
        BeanUtils.copyProperties(storageRoomUpdateDTO, storageRoom);

        // 库房编号不能重复
        StorageRoom entprRoomById = storageRoomMapper.getEntprRoomById(storageRoom.getId());
        // 库房编号被修改
        if (!storageRoomUpdateDTO.getRoomNo().equals(entprRoomById.getRoomNo())) {
            List<StorageRoom> allEntprRooms = storageRoomMapper.getAllEntprRooms(storageRoom.getEntprId());
            for (StorageRoom allEntprRoom : allEntprRooms) {
                // 库房编号重复
                if (allEntprRoom.getRoomNo().equals(storageRoom.getRoomNo())) {
                    return Result.failure(ErrorCodeEnum.SYS_ERR_ROOM_NO_REPEAT);
                }
            }
        }
        int updateEntprRooms = storageRoomMapper.updateEntprRooms(storageRoom);
        if (storageRoomUpdateDTO.getMajorHazardMaterialInsertDTOS() != null) {

            // 清空库区中的介质信息
            majorHazardMaterialMapper.clearMaterial(PartTypeEnum.PART_TYPE_TWO.getCode(),storageRoomUpdateDTO.getId());
            List<MajorHazardMaterialSelectDTO> majorHazardMaterialSelectDTOS = storageRoomUpdateDTO.getMajorHazardMaterialInsertDTOS();
            for (MajorHazardMaterialSelectDTO majorHazardMaterialSelectDTO : majorHazardMaterialSelectDTOS) {
                // 重新新增介质
                MajorHazardMaterial majorHazardMaterial = new MajorHazardMaterial();
                BeanUtils.copyProperties(majorHazardMaterialSelectDTO, majorHazardMaterial);
                majorHazardMaterial.setPartId(storageRoomUpdateDTO.getId());
                majorHazardMaterial.setPartType(PartTypeEnum.PART_TYPE_TWO.getCode());
                majorHazardMaterialMapper.insertSelective(majorHazardMaterial);
            }
        }
        if (updateEntprRooms == CommonConstants.DataBaseOperationStatus.IS_FAILURE) {
            throw new RuntimeException("修改数据失败");
        }
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertEntprRooms(StorageRoomInsertDTO storageRoomInsertDTO) {
        // 新增库区信息
        StorageRoom storageRoom = new StorageRoom();
        BeanUtils.copyProperties(storageRoomInsertDTO, storageRoom);

        List<StorageRoom> allEntprRooms = storageRoomMapper.getAllEntprRooms(storageRoom.getEntprId());
        for (StorageRoom allEntprRoom : allEntprRooms) {
            // 库房编号重复
            if (allEntprRoom.getRoomNo().equals(storageRoom.getRoomNo())) {
                return Result.failure(ErrorCodeEnum.SYS_ERR_ROOM_NO_REPEAT);
            }
        }
        int insertEntprRooms = storageRoomMapper.insertEntprRooms(storageRoom);
        // 查询最近新增的库区
        Long lastId = storageRoomMapper.getLastId();

        if (storageRoomInsertDTO.getMajorHazardMaterialInsertDTOS() != null) {
            // 新增库区介质信息
            List<MajorHazardMaterialInsertDTO> majorHazardMaterialInsertDTOS = storageRoomInsertDTO.getMajorHazardMaterialInsertDTOS();
            for (MajorHazardMaterialInsertDTO majorHazardMaterialInsertDTO : majorHazardMaterialInsertDTOS) {
                MajorHazardMaterial majorHazardMaterial = new MajorHazardMaterial();
                BeanUtils.copyProperties(majorHazardMaterialInsertDTO, majorHazardMaterial);
                majorHazardMaterial.setPartId(lastId);
                majorHazardMaterial.setPartType(PartTypeEnum.PART_TYPE_TWO.getCode());
                majorHazardMaterialMapper.insertSelective(majorHazardMaterial);
            }
        }

        if (insertEntprRooms == CommonConstants.DataBaseOperationStatus.IS_FAILURE) {
            throw new RuntimeException("新增失败");
        }
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteEntprRooms(Long id) {
        // 删除库区
        StorageRoom storageRoom = new StorageRoom();
        storageRoom.setId(id);
        storageRoom.setDelFlag(true);
        int deleteRoom = storageRoomMapper.updateEntprRooms(storageRoom);

        // 删除库区下的介质
        majorHazardMaterialMapper.deleteMaterial(PartTypeEnum.PART_TYPE_TWO.getCode(), id);
        if (deleteRoom == CommonConstants.DataBaseOperationStatus.IS_FAILURE) {
            throw new RuntimeException("删除失败");
        }
        return Result.success();
    }

    @Override
    public Result getEntprRoomById(Long id) {
        StorageRoomSelectDTO storageRoomSelectDTO = new StorageRoomSelectDTO();
        // 查询库区的详情
        StorageRoom entprRoomById = storageRoomMapper.getEntprRoomById(id);
        BeanUtils.copyProperties(entprRoomById, storageRoomSelectDTO);
        // 查询库区下的介质详情
        List<MajorHazardMaterial> majorMaterial = majorHazardMaterialMapper.getMajorMaterial(PartTypeEnum.PART_TYPE_TWO.getCode(), id);
        storageRoomSelectDTO.setMajorHazardMaterials(majorMaterial);
        Long entprId = entprRoomById.getEntprId();
        EntprBasicInfo entprBasicInfo = entprBasicInfoMapper.getEntprBasicInfoById(entprId);
        String entprScope = entprBasicInfo.getEntprScope();
        if (StringUtils.isNotEmpty(entprScope)) {
            entprScope = "{\"data\":" + entprScope + "}";
            JSONObject jsonObject = JSON.parseObject(entprScope);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            List<EntprScopeDTO> entprScopeDTOS = jsonArray.toJavaList(EntprScopeDTO.class);
            storageRoomSelectDTO.setEntprScope(entprScopeDTOS);
        }else{
            storageRoomSelectDTO.setEntprScope(new ArrayList<>());
        }
        return Result.success(storageRoomSelectDTO);
    }
}